import 'package:bot_toast/bot_toast.dart';
import 'package:client_wifi/api/api_server.dart';
import 'package:get/get.dart';

import 'state.dart';

import 'package:wifi_plugin/wifi_plugin.dart';

enum HomeProgressType {
  // 初始状态
  initial,

  // 扫描中
  scanning,

  // 连接设备中
  connectingDevice,

  // 同步中
  syncWifi,

  // 连接中
  connecting,

  // success
  success,
}

/// @description:
/// @author
/// @date: 2025-08-21 17:21:45
class HomeLogic extends GetxController {
  HomeLogic(WifiNetwork wifi, String pwd) {
    state = HomeState(wifi, pwd);
  }
  late final HomeState state;

  Future<void> connectToDevice() async {
    state.progressType.value = HomeProgressType.scanning;
    try {
      final list = await WifiPlugin.scanNetworks();
      for (var i in list) {
        if (i.ssid.startsWith('Raspi')) {
          state.progressType.value = HomeProgressType.connectingDevice;
          final bool isSuccess = await WifiPlugin.connect(
            ssid: i.ssid,
            password: state.deviceWifiPassword,
          );
          if (isSuccess) {
            state.progressType.value = HomeProgressType.syncWifi;
            print('连接成功');
            Map<String, dynamic>? connectedWifi = await ApiServer().addWifi(
              ssid: state.wifi.ssid,
              bssid: state.wifi.bssid,
              password: state.pwd,
            );
            if (connectedWifi != null) {
              print('设备连接wifi 成功$connectedWifi');
              state.deviceConnectedWifi.value = connectedWifi;
              state.progressType.value = HomeProgressType.success;
              return;
            } else {
              BotToast.showText(text: '设置设备wifi 失败');
              state.progressType.value = HomeProgressType.initial;
            }
          } else {
            BotToast.showText(text: '连接设备失败');
          }
          break;
        }
        state.progressType.value = HomeProgressType.initial;
      }
    } catch (e) {
      print('$e');
      state.progressType.value = HomeProgressType.initial;
    }
  }
}
